<template>
  <div class="home-container">
    <stream-preview ref="streamPreviewRef"></stream-preview>
    <room-control
      :given-room-id="givenRoomId"
      @create-room="handleCreateRoom"
      @enter-room="handleEnterRoom"
    ></room-control>
  </div>
</template>

<script setup lang="ts">
import StreamPreview from '@TUIRoom/components/RoomHome/StreamPreview.vue';
import RoomControl from '@TUIRoom/components/RoomHome/RoomControl.vue';
import TUIRoomCore from '@TUIRoom/tui-room-core';
import router from '@/router';
import { useRoute } from 'vue-router';
import { onMounted, Ref, ref } from 'vue';
import { getCustomInfo } from '@/config/basic-info-config';

const route = useRoute();
const streamPreviewRef = ref();

const givenRoomId: Ref<string> = ref((route.query.roomId || '') as string);


function setTUIRoomData(action: string) {
  const roomParam = streamPreviewRef.value.getRoomParam();
  const roomData = {
    action,
    roomMode: 'FreeSpeech',
    roomParam,
  };
  sessionStorage.setItem('tuiRoom-roomInfo', JSON.stringify(roomData));
}

// 创建房间时生成房间号
async function generateRoomId(): Promise<number> {
  const roomId = Math.ceil(Math.random() * 1000000);
  const isRoomExist = await TUIRoomCore.checkRoomExistence(roomId);
  if (isRoomExist) {
    return await generateRoomId();
  }
  return roomId;
}

// 处理点击【创建房间】
async function handleCreateRoom(userId:string, roomId:number|undefined) {
  if (!userId) {
    alert('用户名不能为空！');
    return;
  }
  setTUIRoomData('createRoom');
  // debugger;
  await TUIRoomCore.logout();

  const currentUserInfo = await getCustomInfo(userId);
  if (currentUserInfo) {
    sessionStorage.setItem('tuiRoom-userInfo', JSON.stringify(currentUserInfo));
    const { sdkAppId, userId, userSig } = currentUserInfo;
    // 登录 TUIRoomCore, 只有登录 TUIRoomCore 之后，才可以使用 TUIRoomCore.checkRoomExistence 方法
    console.log(userId);
    await TUIRoomCore.login(sdkAppId, userId, userSig);
  }

  let finalRoomId = roomId;
  if (finalRoomId === 0 || !finalRoomId) finalRoomId = await generateRoomId();

  await router.replace({
    path: 'room',
    query: {
      roomId: finalRoomId,
      userId,
    },
  });
}

// 处理点击【进入房间】
async function handleEnterRoom(userId:string, roomId: number) {
  if (!userId) {
    alert('用户名不能为空！');
    return;
  }
  // debugger;
  await TUIRoomCore.logout();

  const currentUserInfo = await getCustomInfo(userId);
  if (currentUserInfo) {
    sessionStorage.setItem('tuiRoom-userInfo', JSON.stringify(currentUserInfo));
    const { sdkAppId, userId, userSig } = currentUserInfo;
    // 登录 TUIRoomCore, 只有登录 TUIRoomCore 之后，才可以使用 TUIRoomCore.checkRoomExistence 方法
    console.log(userId);
    await TUIRoomCore.login(sdkAppId, userId, userSig);
  }

  const isRoomExist = await TUIRoomCore.checkRoomExistence(roomId);
  if (!isRoomExist) {
    alert('房间不存在，请确认房间号或创建房间！');
    return;
  }
  setTUIRoomData('enterRoom');
  router.replace({
    path: 'room',
    query: {
      roomId,
    },
  });
}

onMounted(async () => {
  // const currentUserInfo = await getBasicInfo();
  // if (currentUserInfo) {
  //   sessionStorage.setItem('tuiRoom-userInfo', JSON.stringify(currentUserInfo));
  //   const { sdkAppId, userId, userSig } = currentUserInfo;
  //   // 登录 TUIRoomCore, 只有登录 TUIRoomCore 之后，才可以使用 TUIRoomCore.checkRoomExistence 方法
  //   await TUIRoomCore.login(sdkAppId, userId, userSig);
  // }
});

</script>

<style lang="scss" scoped>
.home-container {
  width: 100%;
  height: 100%;
  background-color: #010101;
  color: #B3B8C8;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: PingFangSC-Medium;
  .header {
    width: 100%;
    position: absolute;
    top: 0;
    padding: 22px 24px;
    display: flex;
    align-items: center;
    .header-item {
      &:not(:first-child) {
        margin-left: 16px;
      }
    }
  }
}
</style>
